package com.cn.zpark;

import com.cn.zpark.beans.User;
import com.cn.zpark.utils.DruidUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.cn.zpark
 * @ClassName: ServletDemo02
 * @Description:
 * @author: RZS
 * @date: 2022/4/20  10:55
 */
@WebServlet("/sd2.do")
public class ServletDemo02 extends HttpServlet {
    /**
     * 1、从数据库获取用户数据
     * 2、将数据绑定到请求域对象中
     * 3、转发给JSP做处理
     * 4、JSP从请求域中获取数据并展示
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 准备连接信息
        Connection conn = null;
        PreparedStatement stat = null;
        ResultSet res = null;
        List<User> users = new ArrayList<>();


        try {
            // 获取连接对象
            conn = DruidUtils.getConn();
            // 编写sql
            String sql = "select id, uname, pwd from tab1";
            // 创建预编译sql
            stat = conn.prepareStatement(sql);
            // 替换占位符
            // 执行sql
            res = stat.executeQuery();
            // 封装结果
            while (res.next()) {
                // 取出每一条数据封装在user对象中
                User user = new User();
                user.setId(res.getInt("id"));
                user.setUname(res.getString("uname"));
                user.setPwd(res.getString("pwd"));

                System.out.println(user.toString());

                // 添加user对象到list集合中
                users.add(user);

            }
            // 绑定到请求域对象中
            request.setAttribute("users", users);
            // 获取转发器
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/demo08.jsp");
            // 转发到JSP
            requestDispatcher.forward(request, response);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            DruidUtils.close(conn, res, stat);
        }
    }
}
